<?php 

	require_once("fta.201003310000/fta.php");
	
	fta_registerModules(
		array(
			"FTAORM/FTAORM",
			"FTAORM/FTAManyToManyInterface", 
		)
	);
	
	class FTATag extends FTAORM implements FTAManyToManyInterface {

		private $_tablePrefix;
			
		function __construct (Zend_Db_Adapter_Abstract $zdb=null) {
			parent::__construct($zdb);
			
			$this->tableName  = "tag";
			$this->primaryKey = "id";
			$this->tableFields = array(
				"tag",
				"slug"
			);
				
			$this->tableFieldTypes = array(
				"tag"=> "string",
				"slug"=> "string"
			);
				
			$this->tableRequiredFields = array("tag");
			$this->_tablePrefix = "";				
		}

		
		function save($newPrimaryKey=null){
			if(is_null($this->zdb)){
				return true;// this object does not want to be saved at this point in time.. pretend we have been.
			}
			
			if (!isset($this->slug) || is_null($this->slug) || 0 >= strlen($this->slug)){
				$this->slug = $this->getSlugFromTag();
			}
			return parent::save();
		}
		
		//add functions here to get the related stuff.. ie bio and ask
		public function getTablePrefix(){
			return '';// $this->_tablePrefix;
		}
		
		public function getTableBaseName(){
			return $this->tableName;//preg_replace('/^' . $this->getTablePrefix() . "/",'',$this->tableName);
		}
		//
		
		public static function getTagsForString($tagString, Zend_Db_Adapter_Abstract $zdb){
			//split the string, and load/create tags as required..
			$tagArray = array_unique(array_filter(array_map( 'trim',  explode(",",$tagString))));
			return static::getTagsForArray($tagArray, $zdb);
		}
		
		public static function getTagsForSlugs($tagSlugString, Zend_Db_Adapter_Abstract $zdb){
			//split the string, and load/create tags as required..
			$tagSlugArray = array_unique(array_filter(array_map( 'trim',  explode(",",$tagSlugString))));
			return static::getTagsForSlugArray($tagSlugArray, $zdb);
		}
				
		public static function getTagsForArray(array $tagArray, Zend_Db_Adapter_Abstract $zdb){
			//this normalises the array and will turn an aray of strings into tags,
			// or a mixed array of tags and strings to tags
			// or tags to tags..
			// this assumes we have built a sensible list.. the above string, will clean/remove dups..
			// this will not.. 
			$newTagArray = array();
			
			foreach ($tagArray as $tagCandidate){
				$tag = static::mutateToTag($tagCandidate, $zdb);
				if (!is_null($tag))
					array_push($newTagArray,$tag);
			}

			return $newTagArray;
		}
		
		public static function getTagsForSlugArray(array $tagSlugArray, Zend_Db_Adapter_Abstract $zdb){
			//this normalises the array and will turn an aray of strings into tags,
			// or a mixed array of tags and strings to tags
			// or tags to tags..
			// this assumes we have built a sensible list.. the above string, will clean/remove dups..
			// this will not.. 
			$newTagArray = array();
			
			foreach ($tagSlugArray as $tagSlugCandidate){
				$tag = static::getTagForSlug($tagSlugCandidate,$zdb);
				if (!is_null($tag))
					array_push($newTagArray,$tag);
			}

			return $newTagArray;
		}		
		
		public static function mutateToTag($v, Zend_Db_Adapter_Abstract $zdb){
			if (is_string($v)){
				return static::getTagForString($v,$zdb);
			} else if (is_numeric($v)){
				return static::getObjectWithId($v,$zdb);
			} else if ($v instanceof Tag){
				return $v;
			}
			return null;
		}		
				
		
		public static function getTagForString($string, Zend_Db_Adapter_Abstract $zdb ){

			if (!$string)
				return null;
				
			$myClass = get_called_class();
			$vt = new $myClass($zdb);
			
			$zdb->setFetchMode(Zend_Db::FETCH_ASSOC);
			$select = $zdb->select()
            	->from(array('vt' => $vt->tableName) )
				->where('UPPER(vt.tag) = ?', strtoupper($string));
				
			$statement = $select->query();
			$result = $statement->fetchAll();
			
			if ( count($result) > 0) {
				
				$a = static::rowsToObjects($result,$myClass);
				return array_pop( $a );
			} else {
				// be aware.. this returns an empty tag, if it does not find one..
				
				$vt->tag = $string;
				return $vt;
			}
			return null;
		}
		
		public static function getTagForSlug($slug, Zend_Db_Adapter_Abstract $zdb ){

			if (!$slug)
				return null;
				
			$myClass = get_called_class();
			$vt = new $myClass($zdb);
			
			$zdb->setFetchMode(Zend_Db::FETCH_ASSOC);
			$select = $zdb->select()
            	->from(array('vt' => $vt->tableName) )
				->where('UPPER(slug) = ?', strtoupper($slug));
				
			$statement = $select->query();
			$result = $statement->fetchAll();
			
			if ( count($result) > 0) {
				
				$a = static::rowsToObjects($result,$myClass);
				return array_pop( $a );
			} else {
				// be aware.. this returns an empty tag, if it does not find one..
			//no new tags from slugs..	
			//	$vt->tag = $slug;
			//	return $vt;
			}
			return null;
		}
				
		public static function getTagsForContect(FTAORMCMSContent $content, Zend_Db_Adapter_Abstract $zdb ){
			/*
			$myClass = get_called_class();
			
			$vt = new $myClass($zdb);
			
			$zdb->setFetchMode(Zend_Db::FETCH_ASSOC);
			$select = $zdb->select()
            ->from(array('vt' => $vt->tableName) )

            ->join(array('vvt' =>  $video->tablePrefix . $video->tableBaseName . '_' . $vt->tableBaseName ),
                    'vvt.'. $vt->tableBaseName . '_' . $vt->primaryKey .' = vt.' . $vt->primaryKey,
                    array() )

            ->join(array('v' => $video->tableName ),
                    'v.' . $video->primaryKey .' = vvt.' . $video->tableBaseName . '_' .$video->primaryKey ,
                    array())
	             ->where('v.' . $video->primaryKey.' = ?',$video->getPrimaryKey());                    

			$statement = $select->query();
			$result = $statement->fetchAll();
			
			return static::rowsToObjects($result,$myClass);
			*/
			die("whoopsie.. some one did not finish this.. ");
			return array();
		}
		
		
		public static function getObjectsWithIds(array $idArray, Zend_Db_Adapter_Abstract $zdb){
			$objects=array();
			
			foreach($idArray as $id){
				$o = static::getObjectWithId($id,$zdb);
				if ($o){
					$o->zdb = null;//dont want a db in these as they are read only.. 
					array_push($objects,$o);
				}
			}
			return $objects;
		}
		
				
		//possibly add a set tags for (x) here?
		// or push that into the (x).. 
		
		public function __toString(){
			if (isset($this->tag)){
				return $this->tag;
			}
			return "";			
		}
		
		public function validateTag(){
			if(isset($this->tag)){
				$tag = $this->tag;
							
				if (2 > strlen($tag)){
					return "Tags must be 2 or more characters long";	
				}			
			}
		}
		
		public function getSlugFromTag(){		

		   $slug= strtolower(trim($this->tag));

		//TODO: need a cleaner method for removing high byte order chars.. unless we want unicode url evil
		//	$search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u");
		//	$replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u");
		//	$slug = str_replace($search, $replace, $slug);
			
		   			
		   $slug=preg_replace('/[[:punct:]]+/', '', $slug);
		   $slug=preg_replace('/[[:space:]]+/', '-', $slug);
		   		   
		   return $slug;
		}		
		
	}
